package com.jjh.winterframework.core;

import com.jjh.winterframework.annatation.Component;
import com.jjh.winterframework.annatation.ComponentScan;
import com.jjh.winterframework.util.WinterUtils;

import java.io.File;
import java.util.List;

/**
 * 注解解析器，暂时先让它解析@Component  @ComponentScan
 * @author JJH
 */
public class CommonAnnotationProcess {



    public CommonAnnotationProcess(){
        //初始化时，就调用
        try {
            componetScanAnalysis();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 找到标注了@ComponentScan注解的类
     */
    public void componetScanAnalysis() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        List<File> classFiles = WinterUtils.getClassFiles();
        for (File classFile : classFiles) {
            String path = classFile.getPath();
            String className = WinterUtils.getClassName(path);
            //类加载获取类对象
            Class<?> aClass = Class.forName(className);
            ComponentScan componentScan = aClass.getAnnotation(ComponentScan.class);
            if(componentScan!=null){
                //该类上面有这个注解,要获取该注解中的包名信息
                String[] paths = componentScan.packagePath();
                List<File> clsFiles = WinterUtils.getClassFileByPackage(paths);
                componentAnalySis(clsFiles);
            }
        }

    }

    /**
     * 解析带有@Component注解的类
     * @param classFiles
     */
    public void componentAnalySis(List<File> classFiles) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        for (File file : classFiles) {
            String className = WinterUtils.getClassName(file.getPath());
            Class<?> aClass = Class.forName(className);
            Component component = aClass.getAnnotation(Component.class);
            if(component!=null){
                //可以给该类创建对象拉！哈哈哈
                Object obj = aClass.newInstance();
                //默认根据类名首字母小写作为id
                String name = aClass.getName();
                String id = name.substring(0, 1).toLowerCase() + name.substring(1);
                //添加到beanmap中去啦!
                ApplicationContext.getBeans().put(id,obj);
            }
        }
    }




    }




